package com.bayihouse.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bayihouse.annotation.AuthCheck;
import com.bayihouse.common.BaseResponse;
import com.bayihouse.common.DeleteRequest;
import com.bayihouse.common.ErrorCode;
import com.bayihouse.common.ResultUtils;
import com.bayihouse.constant.AdministerConstant;
import com.bayihouse.exception.BusinessException;
import com.bayihouse.exception.ThrowUtils;
import com.bayihouse.model.entity.Administer;
import com.bayihouse.model.entity.Occupant;
import com.bayihouse.model.request.occupant.OccupantAddRequest;
import com.bayihouse.model.request.occupant.OccupantQueryRequest;
import com.bayihouse.model.request.occupant.OccupantUpdateRequest;
import com.bayihouse.model.vo.OccupantVO;
import com.bayihouse.service.AdministerService;
import com.bayihouse.service.OccupantService;
import com.bayihouse.service.RoomService;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.ParseException;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/occupant")
@Slf4j
public class OccupantController {

    @Resource
    private OccupantService occupantService;
    private final static Gson GSON = new Gson();

    @Resource
    private AdministerService administerService;

    @Resource
    private RoomService roomService;


    // endregion

    // region 增删改查

    /**
     * 创建用户
     *
     * @param occupantAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    @AuthCheck(mustRole = AdministerConstant.DEFAULT_ROLE)
    public BaseResponse<Long> addOccupant(@RequestBody OccupantAddRequest occupantAddRequest, HttpServletRequest request) {
        if (occupantAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Occupant occupant = new Occupant();
        List<String> label = occupantAddRequest.getLabel();
        if (label != null) {
            occupant.setLabel(GSON.toJson(label));
        }
        BeanUtils.copyProperties(occupantAddRequest, occupant);
        Administer loginAdminister = administerService.getLoginAdminister(request);
        occupant.setAddUserId(loginAdminister.getId());
        boolean result = occupantService.save(occupant);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(occupant.getId());
    }

    /**
     * 删除用户
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = AdministerConstant.DEFAULT_ROLE)
    public BaseResponse<Boolean> deleteOccupant(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = occupantService.removeById(deleteRequest.getId());
        return ResultUtils.success(b);
    }


    /**
     * 更新用户
     *
     * @param occupantUpdateRequest
     * @param request
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = AdministerConstant.DEFAULT_ROLE)
    public BaseResponse<Boolean> updateOccupant(@RequestBody OccupantUpdateRequest occupantUpdateRequest,
                                                HttpServletRequest request) {
        System.out.println(occupantUpdateRequest);
        if (occupantUpdateRequest == null || occupantUpdateRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Occupant occupant = new Occupant();
        List<String> label = occupantUpdateRequest.getLabel();
        if (label != null) {
            occupant.setLabel(GSON.toJson(label));
        }
        if (occupantUpdateRequest.getStatus() == 1) {
            occupant.setLeavetime(new Date());
        }
        BeanUtils.copyProperties(occupantUpdateRequest, occupant);
        boolean result = occupantService.updateById(occupant);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/get")
    @AuthCheck(mustRole = AdministerConstant.DEFAULT_ROLE)
    public BaseResponse<OccupantVO> getOccupantVOById(long id, HttpServletRequest request) throws ParseException {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Occupant occupant = occupantService.getById(id);
        OccupantVO occupantVO = OccupantVO.objToVO(occupant);
        Administer byId = administerService.getById(occupant.getAddUserId());
        if (byId != null) {
            occupantVO.setAddUserName(byId.getUserName());
        }

        ThrowUtils.throwIf(occupant == null, ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(occupantVO);
    }

    @PostMapping("/getById")
    @AuthCheck(mustRole = AdministerConstant.DEFAULT_ROLE)
    public BaseResponse<Occupant> getOccupantById(long id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Occupant occupant = occupantService.getById(id);
        ThrowUtils.throwIf(occupant == null, ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(occupant);
    }


    /**
     * 分页获取用户列表（仅管理员）
     *
     * @param occupantQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = AdministerConstant.DEFAULT_ROLE)
    public BaseResponse<Page<Occupant>> listOccupantByPage(@RequestBody OccupantQueryRequest occupantQueryRequest,
                                                           HttpServletRequest request) throws ParseException, IOException {
        long current = occupantQueryRequest.getCurrent();
        long size = occupantQueryRequest.getPageSize();
        Page<Occupant> occupantPage = occupantService.page(new Page<>(current, size),
                occupantService.getQueryWrapper(occupantQueryRequest));
        return ResultUtils.success(occupantPage);
    }

    /**
     * 分页获取用户封装列表
     *
     * @param occupantQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    @AuthCheck(mustRole = AdministerConstant.DEFAULT_ROLE)
    public BaseResponse<Page<OccupantVO>> listOccupantVOByPage(@RequestBody OccupantQueryRequest occupantQueryRequest,
                                                               HttpServletRequest request) throws ParseException {
        if (occupantQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long current = occupantQueryRequest.getCurrent();
        long size = occupantQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Occupant> occupantPage = occupantService.page(new Page<>(current, size),
                occupantService.getQueryWrapper(occupantQueryRequest));
        System.out.println(occupantPage.getRecords());
        Page<OccupantVO> occupantVOPage = new Page<>(current, size, occupantPage.getTotal());
        List<OccupantVO> occupantVO = occupantService.getOccupantVOList(occupantPage.getRecords());
        List<Occupant> records = occupantPage.getRecords();
        for (int i = 0; i < records.size(); i++) {
            Administer byId = administerService.getById(occupantVO.get(i).getAddUserId());
            if (byId == null) {
                continue;
            }
            occupantVO.get(i).setAddUserName(byId.getUserName());
        }
        System.out.println(occupantVO);
        occupantVOPage.setRecords(occupantVO);
        return ResultUtils.success(occupantVOPage);
    }

}

